<?php
namespace common\components\behaviors;

use yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use common\components\ActiveRecord2015;
use common\components\UpdateCache;

class CacheBehavior extends Behavior {
    
	
    public function events() {
        return [
        	ActiveRecord::EVENT_AFTER_INSERT => 'updateCache',
        	ActiveRecord::EVENT_AFTER_DELETE => 'updateCache',
        	ActiveRecord::EVENT_AFTER_UPDATE => 'updateCache',
        	ActiveRecord2015::EVENT_UPDATEALL => 'updateCache',
        	ActiveRecord2015::EVENT_DELETEALL => 'updateCache',
        	ActiveRecord2015::EVENT_RUBBISH => 'updateCache',
        	ActiveRecord2015::EVENT_RESTORE => 'updateCache',
        ];
    }
    
    /**
     * 初始化缓存更新器
     * @see \yii\base\Object::init()
     */
    public function init() {
    	set_time_limit(0);
    }
    

    /**
     * 
     * @Title: updateCache
     * @Description: 触发缓存更新事件 
     * @return: return_type
     * @author: kai.gao
     * @date: 2014-12-1 上午10:05:46
     */
    public function updateCache($event) {
    	$model = $this->owner;
    	$class = get_class($this->owner);
    	$action = '';
    	switch ($event->name) {
    		case ActiveRecord::EVENT_AFTER_UPDATE: 
    			$action = 'update'; 
    		break;
    		case ActiveRecord::EVENT_AFTER_DELETE:
    			 $action = 'delete';
    		break;
    		case ActiveRecord2015::EVENT_RUBBISH: 
    			$action = 'rubbish'; 
    		break;
    		case ActiveRecord::EVENT_AFTER_INSERT: 
    			$action = 'insert';
    		break;
    		case ActiveRecord2015::EVENT_RESTORE: 
    			$action = 'restore'; 
    		break;
    		case ActiveRecord2015::EVENT_DELETEALL: 
    			$action = 'delete_all'; 
    		break;
    		case ActiveRecord2015::EVENT_UPDATEALL: 
    			$action = 'update_all'; 
    		break;
    	}
    	$cacheMap = f_p('cacheMap');
    	if (isset($cacheMap[$class])) {
    		foreach ($cacheMap[$class]['mode'] as $method) {
    			$name = [UpdateCache::className(), $method];
	    		is_callable($name) && call_user_func($name, $model, $action, $event);
    		}
    	}
    }
}